from apps.user.dao import UserDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from decimal import Decimal
from apps.pay.order.countAward.gradeAward import countLevelAward

# 计算直推奖
def countVerticalAward(key, order, by, awardType):
    print('计算直推奖')
    baseAward = order.realPay
    _user = UserDao().findOneByObjId(order.user.id)
    _parent = _user.parent
    if not _parent:
        print('上级不存在')
        return
    rank = _parent.rank
    award = 0
    if by == 'money':
        if rank.verticalAward <= 0:
            print('奖金未设置，不予发放')
            return
        award = rank.verticalAward
    elif by == 'rate':
        if rank.verticalAwardRate <= 0:
            print('奖金比例未设置，不予发放')
            return
        award = baseAward * rank.verticalAwardRate
    sendVerticalAward(awardType, _parent, award, order)
    # 计算平级奖励
    if rank.isLevelAward:
        countLevelAward(_parent, award, order, rank, key)
    
# 增加直推奖
def sendVerticalAward(awardType, _parent, award, order):
    print('发放直推奖', _parent, award)
    UserDao().addWallet('incomes', _parent, award)
    UserDao().addWallet('historyIncomes', _parent, award)
    # 新增钱包记录
    data = {}
    data['scene'] = awardType
    data['user'] = _parent.id
    data['fromUser'] = order.user.id
    data['orderId'] = order.orderId
    data['money'] = Decimal(award).quantize(Decimal("0.00"))
    data['payway'] = 'incomes'
    data['changeWay'] = 'add'
    RecordIncomesDao().create(data)